package kr.saeildamil.androidstudy.example02;

import kr.saeildamil.androidstudy.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class AddActivity extends Activity {
	ProgressDialog progressDlg;
	EditText leftEdit;
	EditText rightEdit;
	TextView resultTv;
	final static int REQ_CODE = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ex2_add);
		leftEdit = (EditText)findViewById(R.id.ex2_et_l_value);
		rightEdit = (EditText)findViewById(R.id.ex2_et_r_value);
	}
	
	public void mOnClick(View v){
		switch(v.getId()){
		case R.id.ex2_btncal:
			Intent intent = new Intent(AddActivity.this, CalActivity.class);
			startActivityForResult(intent, REQ_CODE);
			break;
		case R.id.ex2_asyncBtn:
			new CalAsyncTask().execute(
					Integer.parseInt(leftEdit.getText().toString()),
					Integer.parseInt(rightEdit.getText().toString())
					);
			break;
			
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==REQ_CODE){
			if(resultCode == RESULT_OK){
				resultTv = (TextView)findViewById(R.id.ex2_result01);
				resultTv.setText(data.getStringExtra("result"));
			}
		}
	}
	
	private class CalAsyncTask extends AsyncTask<Integer, Void, Integer>{
		@Override
		protected void onPreExecute() {
			progressDlg = ProgressDialog.show(AddActivity.this, "Wait", "Calculating...");
					
		}

		@Override
		protected Integer doInBackground(Integer... params) {
			int result = params[0]+params[1];
			return result;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			progressDlg.dismiss();
			resultTv = (TextView)findViewById(R.id.ex2_result02);
			resultTv.setText(result + "");
		}
    }
}
